package cn.edu.lingnan.servlet.project;

import cn.edu.lingnan.pojo.Project;
import cn.edu.lingnan.service.ProjectService;
import cn.edu.lingnan.service.ProjectServiceImp;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/pageproject", "/queryprojectbyname"})
public class ProjectServlet extends HttpServlet {
    private ProjectService projectService= new ProjectServiceImp();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getServletPath();

        switch (action) {
            case "/pageproject":
                listProjectsByPage(request, response);
                break;
            case "/queryprojectbyname":
                searchProjectsByName(request, response);
                break;
        }
    }

    private void listProjectsByPage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 10;

        if (request.getParameter("page") != null) {
            page = Integer.parseInt(request.getParameter("page"));
        }
        if (request.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        }

        List<Project> projects = projectService.queryAllProjects(page, pageSize);
        for (Project project : projects) {
            System.out.println(project);
        }
        int totalScores = projectService.countProject();
        int totalPage = (int) Math.ceil(totalScores / (double) pageSize);

        request.setAttribute("projects", projects);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("pageSize", pageSize);

        request.getRequestDispatcher("/manager_queryAllProjects.jsp").forward(request, response);
    }

    private void searchProjectsByName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String  projectName = request.getParameter("projectName");


            List<Project> projects= projectService.queryProjectLikeName(projectName);

            request.setAttribute("projects", projects);

            request.setAttribute("currentPage", 1);
            request.setAttribute("totalPage", 1);
            request.setAttribute("pageSize", projects.size());


        request.getRequestDispatcher("/manager_queryAllProjects.jsp").forward(request, response);
    }
}